import { defineStore } from "pinia";
import { ref } from "vue";
import type { menu } from "~/types/menu";
import { initMenu } from "@/data/menu";

export const useMenuStore = defineStore(
  "menu",
  () => {
    const menu_list = ref<menu[]>([]);
    // 拥有权限的菜单
    const menu_list_hasPermission = computed(() => {
      return init_menu_list(menu_list.value);
    });
    // 获取全量菜单
    const getMenu_all = async (cb: any) => {
      const res: {
        [key: string]: any;
      }[] = await $fetch(`/api/system/list`, {
        query: {
          name: "menu",
        },
      });
      if (Array.isArray(res) && res.length > 0) {
        menu_list.value = JSON.parse(res[0].content);
      } else {
        menu_list.value = initMenu.map((item) => ({
          ...item,
          id: typeof item.id === "string" ? Number(item.id) : item.id,
          children: item.children
            ? item.children.map((child) => ({
                ...child,
                id: typeof child.id === "string" ? Number(child.id) : child.id,
              }))
            : undefined,
        }));
      }
      // 回调函数
      if (cb) {
        cb();
      }
    };
    /**
     * 初始化菜单列表（组装index,删除空children）
     *
     * @param menu_list 菜单列表
     * @param parent_index 父级菜单的索引，默认为空字符串
     * @returns 初始化后的菜单列表
     */
    function init_menu_list(menu_list: menu[], parent_index = "") {
      let new_menu_list: menu[] = [];
      const currentUser = useCurrentUserStore().currentUser;
      menu_list.forEach((item, index) => {
        if (!item.menuHide) {
          if (parent_index) {
            item.index = parent_index + "-" + (index + 1);
          } else {
            item.index = index + 1 + "";
          }
          if (item.children && item.children.length > 0) {
            const children = init_menu_list(item.children, item.index);
            item.children = children;
          } else {
            delete item.children;
          }
          // 按权限过滤菜单 -- 超级管理员 或 拥有菜单权限
          if (
            currentUser.ifSuperAdmin ||
            (currentUser.menu_permissionList &&
              currentUser.menu_permissionList.includes(item.path))
          ) {
            new_menu_list.push(item);
          }
        }
      });
      return new_menu_list;
    }
    function clearMenu() {
      menu_list.value = [];
    }
    return {
      menu_list,
      menu_list_hasPermission,
      getMenu_all,
      clearMenu,
    };
  },
  {
    // 默认持久化在 cookie 中
    persist: true,
  }
);
